<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['border-bottom', 'vertical-center',outer_i == 0? 'border-top': '']"
              v-for="(outer,outer_i) in scope.row.children"
              :key="outer.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeThirdLimit(scope.row,outer.id)">{{outer.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(middle,middle_i) in outer.children"
                  :key="middle.id"
                  :class="[middle_i===0? '':'border-top','vertical-center']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeThirdLimit(scope.row,middle.id)"
                    >{{middle.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="inner in middle.children"
                      :key="inner.id"
                      closable
                      @close="removeThirdLimit(scope.row,inner.id)"
                    >{{inner.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列表 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="handleShowSettingDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 设置权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="SettingRightDialogVisible"
        width="50%"
        @close="settingRightDialogClosed"
      >
        <!-- 树形控件 -->
        <el-tree
          :data="rightsList"
          :props="rightsProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="SettingRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allRightsSetting">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created() {
    // 1.发送请求获取角色列表
    this.__getRolesList()
  },
  data() {
    return {
      rolesList: [], // 角色列表数据
      SettingRightDialogVisible: false,
      rightsList: [], // 树形权限所有数据
      rightsProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的keysID
      defKeys: [],
      roleId: '' // 选中角色ID
    }
  },
  methods: {
    // --------------- 发送网络请求 -----------
    async __getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$showToast.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // -------------- 事件监听 ---------------
    async removeThirdLimit(role, rightId) {
      // 提示是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$showToast.info('取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$showToast.success('删除失败')
      }

      this.$showToast.success('删除成功')
      // 重新获取数据,导致页面重新渲染,会关闭.不建议这样做
      // this.__getRolesList()
      role.children = res.data
    },
    // 点击显示设置权限弹框
    async handleShowSettingDialog(role) {
      this.roleId = role.id
      // 显示弹出框
      this.SettingRightDialogVisible = true
      // 发送请求获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$showToast.error('获取权限失败')
      }
      this.rightsList = res.data

      // 获取三级权限的 id 作为选中的值
      this.getLeafKeys(role, this.defKeys)
    },
    // 通过递归的形式, 获取角色下的所有三级权限的id, 并保存在defKeys中
    getLeafKeys(node, arr) {
      // 如果该对象中不存在中不存在属性, 则是三级权限
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(el => {
        this.getLeafKeys(el, arr)
      })
    },
    // 设置权限框关闭的时候, 清空 defKeys数组
    settingRightDialogClosed() {
      this.defKeys = []
    },
    // 点击分配权限
    async allRightsSetting() {
      // 1. 获取全选和半选状态的id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const keysstr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: keysstr }
      )

      if (res.meta.status !== 200) {
        return this.$showToast.error('分配权限失败')
      }
      this.$showToast.success('分配权限成功')
      this.SettingRightDialogVisible = false
      this.__getRolesList()
    }
  }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}

.border-top {
  border-top: 1px solid #eee;
}
.border-bottom {
  border-bottom: 1px solid #eee;
}
.vertical-center {
  display: flex;
  align-items: center;
}
</style>
